package com.lxg.service;

import com.lxg.dao.UserDao;
import com.lxg.pojo.Role;
import com.lxg.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsPasswordService;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import java.util.List;

/**
 * @author 陆小根
 * date: 2022/04/26
 * Description:
 * 实现密码的自动更新  实现UserDetailsPasswordService
 */
@Service
public class MyDetailUserService implements UserDetailsService, UserDetailsPasswordService {

  private final UserDao userDao;

  @Autowired
  public MyDetailUserService(UserDao userDao) {
    this.userDao = userDao;
  }

  @Override
  public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
    User user = userDao.loadUserByUsername(username);
    if (ObjectUtils.isEmpty(user)) throw new UsernameNotFoundException("用户名不存在");
    List<Role> roles = userDao.getRolesByUid(user.getId());
    user.setRoles(roles);
    return user;

  }

  // 自动更新密码   Delegating默认是什么 就使用什么
  @Override // 默认使用DelegatingPasswordEncoder 默认使用使用相对最安全的密码加密 Bcrypt ---> Cxxx
  public UserDetails updatePassword(UserDetails user, String newPassword) {
    Integer result = userDao.updatePassword(user.getUsername(), newPassword);
    if (result == 1) {
      // 查到了
      // 修改密码
      ((User) user).setPassword(newPassword);
    }
    return user;
  }
}
